#include "func.h"

int creat_list(Node_t **phead)
{
    if (phead == NULL)
    {
        printf("入参失败\n");
        return -1;
    }
    *phead = (Node_t*)malloc(sizeof(Node_t));
    if (*phead == NULL)
    {
        printf("内存分配失败\n");
        return -1;
    }
    memset(*phead, 0, sizeof(Node_t));
    return 0;
}

int insert_list(Node_t *phead, int data)
{
    if (phead == NULL)
    {
        printf("入参失败\n");
        return -1;
    }
    Node_t *pnode = NULL;
    creat_list(&pnode);
    if (pnode == NULL)
    {
        printf("内存分配失败\n");
        return -1;
    }
    pnode->data = data;
    pnode->next = phead->next;
    phead->next = pnode;
    return 0;
}

void show_list(Node_t *phead)
{
    if (phead == NULL)
    {
        printf("入参失败\n");
        return;
    }

    Node_t *pnode = phead->next;
    while (pnode != NULL)
    {
        printf("%d ", pnode->data);
        pnode = pnode->next;
    }
    printf("\n");
    
}

int insert_list_by_tail(Node_t *phead, int data)
{
    if (phead == NULL)
    {
        printf("入参失败\n");
        return -1;
    }
    Node_t *pnode = NULL;
    creat_list(&pnode);
    if (pnode == NULL)
    {
        printf("内存分配失败\n");
        return -1;
    }
    
    Node_t *p = phead;
    while (p->next != NULL )
    {
       p = p->next;
    }
    
    pnode->data = data;
    p->next = pnode;
    return 0;
}

int insert_list_by_position(Node_t *phead, int data, int position)
{
    if (phead == NULL)
    {
        printf("入参失败\n");
        return -1;
    }
    if (position < 0)
    {
        printf("position 错误\n");
        return -1;
    }
    
    Node_t *pnode = NULL;
    creat_list(&pnode);
    if (pnode == NULL)
    {
        printf("内存分配失败\n");
        return -1;
    }
    
    Node_t *p = phead;
    while(p)
    {
        if(position != 0)
         {    
            p = p->next;
            position--;
        }
        if(position == 0)
        {
            pnode->data = data;
            pnode->next = p->next;
            p->next = pnode;
            return   0;
        }
       
    }
    printf("position 错误\n");
    return -1;
}

int delete_list_by_head(Node_t *phead)
{
    if (phead == NULL)
    {
        printf("入参失败\n");
        return -1;
    }
    Node_t *ptemp = phead->next;
    if (ptemp == NULL)
    {
        printf("链表为空\n");
        return -1;
    }
    phead->next = ptemp->next;
    free(ptemp);
    ptemp = NULL;
    return 0;
}


int delete_list_by_tail(Node_t *phead)
{
    
    if (phead == NULL)
    {
        printf("入参失败\n");
        return -1;
    }
    Node_t *ptemp = phead;
    while(ptemp->next->next != NULL)
    {
        ptemp = ptemp->next;
    }
    ptemp->next = NULL;
    return 0;

}